package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.CmnBookMerchantDetailActivity;
import com.hemaapp.yjnh.activity.CmnMerchantDetailActivity;
import com.hemaapp.yjnh.activity.FarmerDetailsActivity;
import com.hemaapp.yjnh.activity.MyFarmerActivity;
import com.hemaapp.yjnh.activity.ZouzouCampsiteMerchantDetailActivity;
import com.hemaapp.yjnh.adapter.AttentionAdapter;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.FollowCollect;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 类描述：关注列表Fragment
 * 创建人：GuiyouZhang
 * 创建时间：2016/8/2 20:37
 * 修改备注：
 */
public class AttentionListFragment extends ViewPagerFragment {
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.layout_refresh)
    RefreshLoadmoreLayout layoutRefresh;
    @Bind(R.id.ckbx_all)
    CheckBox ckbxAll;
    @Bind(R.id.btn_cancel)
    Button btnCancel;
    @Bind(R.id.layout_bottom)
    RelativeLayout layoutBottom;

    private User user;
    private int page = 0;
    private String lat = "";//纬度
    private String lng = "";//经度
    private String keytype = "";//获取类型	1:收藏地标商品    2:收藏有机    3:关注田家    4:关注集体    5:收藏粮库
    //6:收藏乐乐    7:收藏走走    8:收藏村游    9:收藏特产    10:收藏更多    11:关注地标商家    12:关注村游商家
    //13:关注乐乐商家    14:关注特产商家    15:关注粮库商家    16:关注走走商家    18:关注更多商家    22:收藏田家农货
    //23:收藏田家定制

    private ArrayList<FollowCollect> mBlogs = new ArrayList<>();
    private ArrayList<FollowCollect> delCollects = new ArrayList<>();//已经选择准备删除的商品
    private AttentionAdapter mAdapter;
    private boolean isEdit = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_collection);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        lat = XtomSharedPreferencesUtil.get(getActivity(), "lat");
        lng = XtomSharedPreferencesUtil.get(getActivity(), "lng");
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnCancel.setText("取消关注");
        layoutRefresh.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().followCollectList(user.getToken(), keytype, user.getId(), lng, lat, page + "");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().followCollectList(user.getToken(), keytype, user.getId(), lng, lat, page + "");
            }
        });
        if (keytype.equals("3")) {
            layoutRefresh.setBackgroundColor(0xfff0f0f0);
        }else {
            layoutRefresh.setBackgroundColor(0xffffffff);
        }
    }

    public void setKeytype(String keytype) {
        this.keytype = keytype;
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
        mAdapter.setEdit(edit);
        mAdapter.notifyDataSetChanged();
        if (isEdit)
            layoutBottom.setVisibility(View.VISIBLE);
        else
            layoutBottom.setVisibility(View.GONE);
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void setListener() {
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FOLLOW_COLLECT_LIST:
            case FOLLOW_COLLECT_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FOLLOW_COLLECT_LIST:
            case FOLLOW_COLLECT_SAVEOPERATE:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作成功!");
                //从本地删除要取消收藏的商品，也可以刷新重新加载页面
                for (FollowCollect item : delCollects) {
                    mBlogs.remove(item);
                }
                delCollects.clear();
                mAdapter.notifyDataSetChanged();
                ckbxAll.setChecked(false);
                break;
            case FOLLOW_COLLECT_LIST:
                String page = netTask.getParams().get("page");
                @SuppressWarnings("unchecked")
                HemaPageArrayResult<FollowCollect> fResult = (HemaPageArrayResult<FollowCollect>) baseResult;
                if (fResult == null || fResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    layoutRefresh.refreshSuccess();
                    mBlogs.clear();
                    mBlogs.addAll(fResult.getObjects());
                } else {// 更多
                    layoutRefresh.loadmoreSuccess();
                    if (fResult.getObjects().size() > 0) {
                        mBlogs.addAll(fResult.getObjects());
                    } else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败," + baseResult.getMsg());
                break;
            case FOLLOW_COLLECT_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "操作失败," + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败，请稍后再试");
                break;
            case FOLLOW_COLLECT_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(getActivity(), "操作失败，请稍后再试");
                break;
        }
    }

    public AttentionAdapter getAdapter() {
        return mAdapter;
    }

    private void refreshData(final int failed) {
        if (mAdapter == null) {
            int type = 1;
            if (keytype.equals("3"))
                type = 2;
            mAdapter = new AttentionAdapter(getActivity(), mBlogs, type);
            mAdapter.setEmptyString("暂无关注");
            mAdapter.setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    FollowCollect blog = mBlogs.get(position);
                    if (isEdit) {
                        if (blog.isCheck()) {
                            delCollects.remove(blog);
                            blog.setCheck(false);
                        } else {
                            blog.setCheck(true);
                            delCollects.add(blog);
                        }
                        mAdapter.notifyDataSetChanged();
                        if (delCollects.size() == mBlogs.size())
                            ckbxAll.setChecked(true);
                        else
                            ckbxAll.setChecked(false);
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("client_id", mBlogs.get(position).getSeller_id());
                        if (keytype.equals("3")) {
                            intent.putExtra("client_id", mBlogs.get(position).getClient_id());
                            intent.setClass(getActivity(), FarmerDetailsActivity.class);
                            User user = BaseApplication.getInstance().getUser();
                            if (user != null) {
                                String id = user.getId();
                                if (id.equals(mBlogs.get(position).getClient_id())) {
                                    intent.setClass(getActivity(), MyFarmerActivity.class);
                                }
                            }
                        }else if (keytype.equals("12") || keytype.equals("13") || keytype.equals("16")) {//预约类商家
                            String role = mBlogs.get(position).getRole();
                            if (!isNull(role) && role.equals("11"))//走走露营商家
                                intent.setClass(getActivity(), ZouzouCampsiteMerchantDetailActivity.class);
                            else
                                intent.setClass(getActivity(), CmnBookMerchantDetailActivity.class);
                        }else
                            intent.setClass(getActivity(), CmnMerchantDetailActivity.class);
                        startActivity(intent);
                    }
                }
            });
            listview.setAdapter(mAdapter);
        } else
            mAdapter.notifyDataSetChanged();
        mAdapter.setFailtype(failed);
    }

    @Override
    public void fetchData() {
        getNetWorker().followCollectList(user.getToken(), keytype, user.getId(), lng, lat, page+"");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.ckbx_all, R.id.btn_cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                if (0 == delCollects.size()) {
                    XtomToastUtil.showShortToast(getActivity(), "请至少选择一个商家");
                    break;
                }
                HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
                hbDialog.setText("确定取消关注?");
                hbDialog.setLeftButtonText("取消");
                hbDialog.setRightButtonText("确定");
                hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        StringBuffer tempt = new StringBuffer();
                        for (FollowCollect item:delCollects) {
                            if (!isNull(item.getSeller_id()))//非田家
                                tempt.append(item.getSeller_id()).append(",");
                            else//关注的田家
                                tempt.append(item.getClient_id()).append(",");
                        }
                        tempt.deleteCharAt(tempt.length()-1);
                        getNetWorker().FolColOperate(user.getToken(), "1", "2", tempt.toString());
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.ckbx_all:
                boolean allCheck = delCollects.size() >= mBlogs.size() ? true : false;
                for (FollowCollect item : mBlogs) {
                    item.setCheck(!allCheck);
                }
                delCollects.clear();
                if (!allCheck) {//如果之前不是全选
                    delCollects.addAll(mBlogs);
                }
                mAdapter.notifyDataSetChanged();
                break;
        }
    }
}
